"use client";
import React, { useState } from 'react';
import { useTranslations } from 'next-intl';
import { useRouter } from 'next/navigation';
import { Eye, EyeOff, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { signInWithEmail, signUpWithEmail, resetPassword, googleSignIn } from '@/controller/auth';
import { toast } from "sonner";
export function AuthForm() {
  const t = useTranslations('auth');
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showPassword, setShowPassword] = useState(false);
  const [showResetForm, setShowResetForm] = useState(false);
  const [resetEmailSent, setResetEmailSent] = useState(false);
  const [registerSuccess, setRegisterSuccess] = useState<{ success: boolean; message?: string }>({ success: false });

  // 表单状态
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  // 处理登录
  const handleSignIn = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    setIsLoading(true);

    try {
      const { data, error } = await signInWithEmail(email, password);
      if (error) {
        // 处理认证错误
        console.error('登录失败:', error);
        // 检查错误代码或错误消息
        if (error.code === 'invalid_credentials' ||
          (error.message && error.message.includes('Invalid login credentials'))) {
          setError(t('invalidCredentials'));
          return;
        }
        throw error;
      }

      if (data.user) {
        // 登录成功，重定向到仪表板
        toast.success('Login successfully logged in');
        router.push('/');
      }
    } catch (err: Error | unknown) {
      console.error('登录失败:', err);
      setError(err instanceof Error ? err.message : t('loginFailed'));
    } finally {
      setIsLoading(false);
    }
  };

  // 处理谷歌登录
  const handleGoogleSignIn = async () => {
    setError(null);
    setIsLoading(true);

    try {
      const { error } = await googleSignIn()

      if (error) {
        throw error;
      }

      // 谷歌登录是通过重定向完成的，不需要在这里处理成功回调
    } catch (err: Error | unknown) {
      console.error('谷歌登录失败:', err);
      setError(err instanceof Error ? err.message : t('googleSignInFailed'));
      setIsLoading(false);
    }
  };

  // 处理注册
  const handleSignUp = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    setRegisterSuccess({ success: false }); // 重置注册成功状态
    setIsLoading(true);

    try {
      const { error } = await signUpWithEmail(email, password);

      if (error) {
        throw error;
      }
      // 注册成功，显示确认邮件提示
      setRegisterSuccess({
        success: true,
        message: t('verificationEmailSent')
      });
    } catch (err: Error | unknown) {
      console.error('注册失败:', err);
      setError(err instanceof Error ? err.message : t('signupFailed'));
    } finally {
      setIsLoading(false);
    }
  };

  // 处理密码重置
  const handleResetPassword = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    setIsLoading(true);

    try {
      const { error } = await resetPassword(email);

      if (error) {
        throw error;
      }

      // 重置邮件发送成功
      setResetEmailSent(true);
    } catch (err: Error | unknown) {
      console.error('密码重置失败:', err);
      setError(err instanceof Error ? err.message : t('resetPasswordFailed'));
    } finally {
      setIsLoading(false);
    }
  };

  // 重置密码表单
  if (showResetForm) {
    return (
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>{t('resetPassword')}</CardTitle>
          <CardDescription>{t('resetInstructions')}</CardDescription>
        </CardHeader>
        <CardContent>
          {error && (
            <Alert variant="destructive" className="mb-4">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {resetEmailSent ? (
            <div className="text-center py-4">
              <p className="mb-4">{t('resetEmailSent')}</p>
              <Button onClick={() => setShowResetForm(false)}>{t('backToLogin')}</Button>
            </div>
          ) : (
            <form onSubmit={handleResetPassword}>
              <div className="grid gap-4">
                <div className="grid gap-2">
                  <Label htmlFor="reset-email">{t('email')}</Label>
                  <Input
                    id="reset-email"
                    type="email"
                    value={email}
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
                    placeholder="name@example.com"
                    required
                  />
                </div>
                <Button type="submit" disabled={isLoading} className="w-full">
                  {isLoading ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      {t('processing')}
                    </>
                  ) : (
                    t('sendResetLink')
                  )}
                </Button>
              </div>
            </form>
          )}
        </CardContent>
        <CardFooter>
          <Button variant="ghost" onClick={() => setShowResetForm(false)} className="w-full">
            {t('backToLogin')}
          </Button>
        </CardFooter>
      </Card>
    );
  }

  // 登录/注册表单
  return (
    <Card className="w-full max-w-md">
      <Tabs defaultValue="login">
        <CardHeader>
          <div className="flex justify-end items-center">
            {/* <CardTitle>{t('authentication')}</CardTitle> */}
            <TabsList>
              <TabsTrigger value="login">{t('signIn')}</TabsTrigger>
              <TabsTrigger value="register">{t('signUp')}</TabsTrigger>
            </TabsList>
          </div>
          {/* <CardDescription>{t('authDescription')}</CardDescription> */}
        </CardHeader>
        <CardContent>
          {error && (
            <Alert variant="destructive" className="mb-4">
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {registerSuccess.success && (
            <Alert variant="default" className="mb-4 bg-green-50 text-green-800 border-green-200">
              <AlertDescription>
                <div className="font-semibold">{t('registrationSuccessful')}</div>
                <div>{registerSuccess.message}</div>
              </AlertDescription>
            </Alert>
          )}

          <TabsContent value="login">
            <form onSubmit={handleSignIn}>
              <div className="grid gap-4">
                <div className="grid gap-2">
                  <Label htmlFor="login-email">{t('email')}</Label>
                  <Input
                    id="login-email"
                    type="email"
                    value={email}
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
                    placeholder="name@example.com"
                    required
                  />
                </div>
                <div className="grid gap-2">
                  <div className="flex items-center justify-between">
                    <Label htmlFor="login-password">{t('password')}</Label>
                    <Button
                      type="button"
                      variant="link"
                      className="px-0 h-auto text-xs"
                      onClick={() => setShowResetForm(true)}
                    >
                      {t('forgotPassword')}
                    </Button>
                  </div>
                  <div className="relative">
                    <Input
                      id="login-password"
                      type={showPassword ? "text" : "password"}
                      value={password}
                      onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}
                      required
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="absolute right-0 top-0 h-full px-3"
                      onClick={() => setShowPassword(!showPassword)}
                    >
                      {showPassword ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                      <span className="sr-only">
                        {showPassword ? t('hidePassword') : t('showPassword')}
                      </span>
                    </Button>
                  </div>
                </div>
                <Button type="submit" disabled={isLoading} className="w-full">
                  {isLoading ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      {t('processing')}
                    </>
                  ) : (
                    t('signIn')
                  )}
                </Button>

                <div className="relative my-4">
                  <div className="absolute inset-0 flex items-center">
                    <span className="w-full border-t" />
                  </div>
                  <div className="relative flex justify-center text-xs uppercase">
                    <span className="bg-background px-2 text-muted-foreground">
                      {t('orContinueWith')}
                    </span>
                  </div>
                </div>

                <Button
                  variant="outline"
                  type="button"
                  disabled={isLoading}
                  className="w-full"
                  onClick={handleGoogleSignIn}
                >
                  <svg xmlns="http://www.w3.org/2000/svg" className="mr-2 h-4 w-4" viewBox="0 0 48 48">
                    <path fill="#FFC107" d="M43.611,20.083H42V20H24v8h11.303c-1.649,4.657-6.08,8-11.303,8c-6.627,0-12-5.373-12-12c0-6.627,5.373-12,12-12c3.059,0,5.842,1.154,7.961,3.039l5.657-5.657C34.046,6.053,29.268,4,24,4C12.955,4,4,12.955,4,24c0,11.045,8.955,20,20,20c11.045,0,20-8.955,20-20C44,22.659,43.862,21.35,43.611,20.083z" />
                    <path fill="#FF3D00" d="M6.306,14.691l6.571,4.819C14.655,15.108,18.961,12,24,12c3.059,0,5.842,1.154,7.961,3.039l5.657-5.657C34.046,6.053,29.268,4,24,4C16.318,4,9.656,8.337,6.306,14.691z" />
                    <path fill="#4CAF50" d="M24,44c5.166,0,9.86-1.977,13.409-5.192l-6.19-5.238C29.211,35.091,26.715,36,24,36c-5.202,0-9.619-3.317-11.283-7.946l-6.522,5.025C9.505,39.556,16.227,44,24,44z" />
                    <path fill="#1976D2" d="M43.611,20.083H42V20H24v8h11.303c-0.792,2.237-2.231,4.166-4.087,5.571c0.001-0.001,0.002-0.001,0.003-0.002l6.19,5.238C36.971,39.205,44,34,44,24C44,22.659,43.862,21.35,43.611,20.083z" />
                  </svg>
                  {t('signInWithGoogle')}
                </Button>
              </div>
            </form>
          </TabsContent>

          <TabsContent value="register">
            <form onSubmit={handleSignUp}>
              <div className="grid gap-4">
                <div className="grid gap-2">
                  <Label htmlFor="register-email">{t('email')}</Label>
                  <Input
                    id="register-email"
                    type="email"
                    value={email}
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEmail(e.target.value)}
                    placeholder="name@example.com"
                    required
                  />
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="register-password">{t('password')}</Label>
                  <div className="relative">
                    <Input
                      id="register-password"
                      type={showPassword ? "text" : "password"}
                      value={password}
                      onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPassword(e.target.value)}
                      required
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="icon"
                      className="absolute right-0 top-0 h-full px-3"
                      onClick={() => setShowPassword(!showPassword)}
                    >
                      {showPassword ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                      <span className="sr-only">
                        {showPassword ? t('hidePassword') : t('showPassword')}
                      </span>
                    </Button>
                  </div>
                </div>
                <Button type="submit" disabled={isLoading} className="w-full">
                  {isLoading ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      {t('processing')}
                    </>
                  ) : (
                    t('signUp')
                  )}
                </Button>
              </div>
            </form>
          </TabsContent>
        </CardContent>
      </Tabs>
    </Card>
  );
}